<template>
  <div class="project-dashboard">
    <!-- 页面头部 -->
    <div class="dashboard-header">
      <div class="header-content">
        <h1 class="page-title">
          <el-icon><Management /></el-icon>
          项目管理主页
        </h1>
        <div class="header-actions">
          <el-button type="primary" @click="showCreateProject = true">
            <el-icon><Plus /></el-icon>
            新建项目
          </el-button>
          <el-button @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6" v-for="stat in statsData" :key="stat.key">
          <el-card class="stat-card" :class="stat.type">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon :size="32"><component :is="stat.icon" /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stat.value }}</div>
                <div class="stat-label">{{ stat.label }}</div>
                <div class="stat-trend" :class="stat.trend">
                  <el-icon><component :is="stat.trendIcon" /></el-icon>
                  {{ stat.trendValue }}
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 主要内容区域 -->
    <el-row :gutter="20" class="main-content">
      <!-- 左侧内容 -->
      <el-col :xs="24" :lg="16">
        <!-- 项目进度图表 -->
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>项目进度概览</span>
              <el-select v-model="selectedTimeRange" size="small" style="width: 120px">
                <el-option label="本月" value="month" />
                <el-option label="本季度" value="quarter" />
                <el-option label="本年" value="year" />
              </el-select>
            </div>
          </template>
          <div ref="progressChart" class="chart-container"></div>
        </el-card>

        <!-- 项目列表 -->
        <el-card class="project-list-card">
          <template #header>
            <div class="card-header">
              <span>进行中的项目</span>
              <el-link type="primary" @click="$router.push('/project/list')">查看全部</el-link>
            </div>
          </template>
          <el-table :data="activeProjects" style="width: 100%" @row-click="viewProject">
            <el-table-column prop="name" label="项目名称" min-width="200">
              <template #default="{ row }">
                <div class="project-name">
                  <el-tag :type="getStatusType(row.status)" size="small">{{ row.status }}</el-tag>
                  <span class="name">{{ row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="manager" label="项目经理" width="120" />
            <el-table-column prop="progress" label="进度" width="150">
              <template #default="{ row }">
                <div class="progress-cell">
                  <el-progress :percentage="row.progress" :stroke-width="8" :show-text="false" />
                  <span class="progress-text">{{ row.progress }}%</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="endDate" label="预计完成" width="120" />
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button type="text" size="small" @click.stop="viewProject(row)">
                  查看
                </el-button>
                <el-button type="text" size="small" @click.stop="editProject(row)">
                  编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 右侧内容 -->
      <el-col :xs="24" :lg="8">
        <!-- 快捷操作 -->
        <el-card class="quick-actions-card">
          <template #header>
            <span>快捷操作</span>
          </template>
          <div class="quick-actions">
            <div class="action-item" @click="$router.push('/project/initiation')">
              <el-icon><DocumentAdd /></el-icon>
              <span>项目立项</span>
            </div>
            <div class="action-item" @click="$router.push('/project/planning')">
              <el-icon><Calendar /></el-icon>
              <span>项目计划</span>
            </div>
            <div class="action-item" @click="$router.push('/project/resource')">
              <el-icon><User /></el-icon>
              <span>资源管理</span>
            </div>
            <div class="action-item" @click="$router.push('/project/progress')">
              <el-icon><TrendCharts /></el-icon>
              <span>进度跟踪</span>
            </div>
            <div class="action-item" @click="$router.push('/project/cost')">
              <el-icon><Money /></el-icon>
              <span>成本控制</span>
            </div>
            <div class="action-item" @click="$router.push('/project/risk')">
              <el-icon><Warning /></el-icon>
              <span>风险管理</span>
            </div>
          </div>
        </el-card>

        <!-- 最近活动 -->
        <el-card class="recent-activities-card">
          <template #header>
            <span>最近活动</span>
          </template>
          <el-timeline>
            <el-timeline-item
              v-for="activity in recentActivities"
              :key="activity.id"
              :timestamp="activity.time"
              :type="activity.type"
            >
              <div class="activity-content">
                <div class="activity-title">{{ activity.title }}</div>
                <div class="activity-desc">{{ activity.description }}</div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>

        <!-- 项目状态分布 -->
        <el-card class="status-chart-card">
          <template #header>
            <span>项目状态分布</span>
          </template>
          <div ref="statusChart" class="chart-container small"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新建项目对话框 -->
    <el-dialog v-model="showCreateProject" title="新建项目" width="600px">
      <el-form :model="newProject" :rules="projectRules" ref="projectForm" label-width="100px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="newProject.name" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目描述" prop="description">
          <el-input v-model="newProject.description" type="textarea" :rows="3" placeholder="请输入项目描述" />
        </el-form-item>
        <el-form-item label="项目经理" prop="manager">
          <el-select v-model="newProject.manager" placeholder="请选择项目经理" style="width: 100%">
            <el-option label="张三" value="张三" />
            <el-option label="李四" value="李四" />
            <el-option label="王五" value="王五" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker v-model="newProject.startDate" type="date" placeholder="选择开始日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker v-model="newProject.endDate" type="date" placeholder="选择结束日期" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateProject = false">取消</el-button>
        <el-button type="primary" @click="createProject">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import {
  Management,
  Plus,
  Refresh,
  DocumentAdd,
  Calendar,
  User,
  TrendCharts,
  Money,
  Warning,
  ArrowUp,
  ArrowDown,
  Folder,
  Timer,
  Check,
  Close
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 响应式数据
const showCreateProject = ref(false)
const selectedTimeRange = ref('month')
const progressChart = ref(null)
const statusChart = ref(null)
const projectForm = ref(null)

// 统计数据
const statsData = ref([
  {
    key: 'total',
    label: '总项目数',
    value: 24,
    icon: 'Folder',
    type: 'primary',
    trend: 'up',
    trendIcon: 'ArrowUp',
    trendValue: '+12%'
  },
  {
    key: 'active',
    label: '进行中',
    value: 8,
    icon: 'Timer',
    type: 'warning',
    trend: 'up',
    trendIcon: 'ArrowUp',
    trendValue: '+5%'
  },
  {
    key: 'completed',
    label: '已完成',
    value: 15,
    icon: 'Check',
    type: 'success',
    trend: 'up',
    trendIcon: 'ArrowUp',
    trendValue: '+8%'
  },
  {
    key: 'delayed',
    label: '延期项目',
    value: 1,
    icon: 'Close',
    type: 'danger',
    trend: 'down',
    trendIcon: 'ArrowDown',
    trendValue: '-2%'
  }
])

// 进行中的项目
const activeProjects = ref([
  {
    id: 1,
    name: 'ERP系统升级项目',
    manager: '张三',
    status: '进行中',
    progress: 75,
    endDate: '2024-03-15'
  },
  {
    id: 2,
    name: '移动端APP开发',
    manager: '李四',
    status: '进行中',
    progress: 45,
    endDate: '2024-04-20'
  },
  {
    id: 3,
    name: '数据中心建设',
    manager: '王五',
    status: '计划中',
    progress: 20,
    endDate: '2024-05-30'
  }
])

// 最近活动
const recentActivities = ref([
  {
    id: 1,
    title: '项目里程碑完成',
    description: 'ERP系统升级项目第二阶段完成',
    time: '2024-01-15 14:30',
    type: 'success'
  },
  {
    id: 2,
    title: '风险预警',
    description: '移动端APP开发项目存在延期风险',
    time: '2024-01-14 09:15',
    type: 'warning'
  },
  {
    id: 3,
    title: '资源调整',
    description: '数据中心建设项目增加2名开发人员',
    time: '2024-01-13 16:45',
    type: 'primary'
  }
])

// 新建项目表单
const newProject = reactive({
  name: '',
  description: '',
  manager: '',
  startDate: '',
  endDate: ''
})

// 表单验证规则
const projectRules = {
  name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入项目描述', trigger: 'blur' }],
  manager: [{ required: true, message: '请选择项目经理', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }]
}

// 方法
const refreshData = () => {
  ElMessage.success('数据刷新成功')
}

const getStatusType = (status) => {
  const statusMap = {
    '进行中': 'warning',
    '已完成': 'success',
    '计划中': 'info',
    '已暂停': 'danger'
  }
  return statusMap[status] || 'info'
}

const viewProject = (project) => {
  router.push(`/project/detail/${project.id}`)
}

const editProject = (project) => {
  router.push(`/project/edit/${project.id}`)
}

const createProject = async () => {
  try {
    await projectForm.value.validate()
    // 这里应该调用API创建项目
    ElMessage.success('项目创建成功')
    showCreateProject.value = false
    // 重置表单
    Object.assign(newProject, {
      name: '',
      description: '',
      manager: '',
      startDate: '',
      endDate: ''
    })
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 初始化图表
const initProgressChart = () => {
  const chart = echarts.init(progressChart.value)
  const option = {
    title: {
      text: '项目进度趋势',
      left: 'center',
      textStyle: {
        fontSize: 14,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['计划进度', '实际进度'],
      bottom: 0
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [
      {
        name: '计划进度',
        type: 'line',
        data: [20, 35, 50, 65, 80, 95],
        smooth: true,
        lineStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '实际进度',
        type: 'line',
        data: [15, 30, 45, 60, 75, 85],
        smooth: true,
        lineStyle: {
          color: '#67C23A'
        }
      }
    ]
  }
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const initStatusChart = () => {
  const chart = echarts.init(statusChart.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    series: [
      {
        name: '项目状态',
        type: 'pie',
        radius: '70%',
        center: ['50%', '50%'],
        data: [
          { value: 8, name: '进行中', itemStyle: { color: '#E6A23C' } },
          { value: 15, name: '已完成', itemStyle: { color: '#67C23A' } },
          { value: 1, name: '延期', itemStyle: { color: '#F56C6C' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          fontSize: 12
        }
      }
    ]
  }
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 生命周期
onMounted(() => {
  nextTick(() => {
    initProgressChart()
    initStatusChart()
  })
})
</script>

<style scoped>
.project-dashboard {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.dashboard-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.stat-card.primary .stat-icon {
  background: linear-gradient(135deg, #409EFF, #66B1FF);
}

.stat-card.warning .stat-icon {
  background: linear-gradient(135deg, #E6A23C, #EEBE77);
}

.stat-card.success .stat-icon {
  background: linear-gradient(135deg, #67C23A, #85CE61);
}

.stat-card.danger .stat-icon {
  background: linear-gradient(135deg, #F56C6C, #F78989);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin: 4px 0;
}

.stat-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-trend.up {
  color: #67C23A;
}

.stat-trend.down {
  color: #F56C6C;
}

.main-content {
  margin-bottom: 20px;
}

.chart-card,
.project-list-card,
.quick-actions-card,
.recent-activities-card,
.status-chart-card {
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.chart-container.small {
  height: 200px;
}

.project-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.project-name .name {
  font-weight: 500;
}

.progress-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-text {
  font-size: 12px;
  color: #909399;
  min-width: 35px;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 16px;
  border: 1px solid #EBEEF5;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  background: #fafafa;
}

.action-item:hover {
  border-color: #409EFF;
  background: #ecf5ff;
  color: #409EFF;
}

.action-item span {
  font-size: 12px;
  font-weight: 500;
}

.activity-content {
  margin-bottom: 8px;
}

.activity-title {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.activity-desc {
  font-size: 12px;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .project-dashboard {
    padding: 10px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .stat-content {
    flex-direction: column;
    text-align: center;
    gap: 8px;
  }
  
  .quick-actions {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .action-item {
    padding: 12px 8px;
  }
  
  .chart-container {
    height: 250px;
  }
}

@media (max-width: 480px) {
  .quick-actions {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>